﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;
using Model;
using Repository;
using UI.Areas.Admin.Models;
using UI.Helper;

namespace UI.Areas.Admin.Controllers
{
    public class FurnitureImageController : Controller
    {
        public ActionResult Index(int id)
        {
            try
            {
                if (id <= 0)
                    return RedirectToAction("Index", "FurnitureProduct");

                var imgRepository = RepositoryManager.CreateTKNTImageRepository();

                var lst = Paging(id, 1, imgRepository) ?? new List<tkntImage>();

                ViewData["ProductId"] = id;

                return View(lst);
            }
            catch (Exception)
            {
                return RedirectToAction("Index", "FurnitureProduct");
            }
        }

        public ActionResult PagingData(int pageIndex, int productId)
        {
            var repository = RepositoryManager.CreateTKNTImageRepository();

            var lst = Paging(productId, pageIndex, repository) ?? new List<tkntImage>();

            return View("Index", lst);
        }

        public ActionResult Delete(int id)
        {
            var repository = RepositoryManager.CreateTKNTImageRepository();

            var objDelete = repository.GetByIdHaveProduct(id);

            var productId = 0;

            if (objDelete != null)
            {
                productId = objDelete.Product.Id;

                repository.Delete(objDelete);

                TempData[Constants.MESSAGE] = "Đã xóa thành công";
            }

            return RedirectToAction("Index", new { id = productId });
        }

        public ActionResult DeleteAll(string id)
        {
            string[] arrId = id.Split(',');

            var repository = RepositoryManager.CreateTKNTImageRepository();

            var productId = 0;

            foreach (var s in arrId)
            {
                var objDelete = repository.GetByIdHaveProduct(Convert.ToInt32(s));

                if (objDelete != null)
                {
                    productId = objDelete.Product.Id;

                    repository.Delete(objDelete);
                }

                TempData[Constants.MESSAGE] = "Đã xóa thành công";
            }

            return RedirectToAction("Index", new { id = productId });
        }

        public ActionResult Edit(int id)
        {
            var repository = RepositoryManager.CreateTKNTImageRepository();

            var objEdit = repository.GetByIdHaveProduct(id);

            if (objEdit != null)
            {
                var model = new FurnitureImageModel() { Url = objEdit.Url, ProductId = objEdit.Product.Id, IsAvatar = objEdit.IsAvatar };

                return View(model);
            }

            return View("Index");
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(HttpPostedFileBase uploadFile)
        {
            FurnitureImageModel model = new FurnitureImageModel();
            TryUpdateModel(model);

            var repository = RepositoryManager.CreateTKNTImageRepository();

            if (model != null)
            {
                var objEdit = repository.GetById(model.Id);

                string fileName = "";
                if (uploadFile != null && uploadFile.ContentLength > 0)
                {
                    fileName = Path.GetFileName(uploadFile.FileName);
                    string filePath = Path.Combine(HttpContext.Server.MapPath("~/Uploads"), fileName);
                    if (!string.IsNullOrEmpty(objEdit.Url))
                        System.IO.File.Delete(Path.Combine(HttpContext.Server.MapPath("~/Uploads"), objEdit.Url));
                    uploadFile.SaveAs(filePath);
                }

                if (objEdit != null)
                {
                    objEdit.Url = fileName;

                    objEdit.IsAvatar = model.IsAvatar;

                    repository.Update(objEdit);

                    TempData[Constants.MESSAGE] = "Đã cập nhật thành công";
                }

                return RedirectToAction("Index", new { id = model.ProductId });
            }

            return View();
        }

        public ActionResult Add(int id)
        {
            var model = new FurnitureImageModel() { ProductId = id };

            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Add(HttpPostedFileBase uploadFile)
        {
            string fileName = "";
            if (uploadFile != null && uploadFile.ContentLength > 0)
            {
                fileName = Path.GetFileName(uploadFile.FileName);
                string filePath = Path.Combine(HttpContext.Server.MapPath("~/Uploads"), fileName);
                uploadFile.SaveAs(filePath);
            }

            FurnitureImageModel model = new FurnitureImageModel();
            TryUpdateModel(model);

            var repository = RepositoryManager.CreateTKNTImageRepository();

            if (model != null)
            {
                var proReporisitory = RepositoryManager.CreateTKNTProductRepository();

                var objProduct = proReporisitory.GetById(model.ProductId);

                var objInsert = new tkntImage() { Product = objProduct, Url = fileName, IsAvatar = model.IsAvatar };

                repository.Insert(objInsert);

                TempData[Constants.MESSAGE] = "Đã thêm thành công";

                return RedirectToAction("Index", new { id = model.ProductId });
            }

            return View();
        }

        private List<tkntImage> Paging(int productId, int pageIndex, tkntImageRepository repository)
        {
            var totalPage = repository.GetTotalPage(productId, Constants.NUM_OF_ROWS);

            ViewData[Constants.TOTAL_PAGE] = totalPage;

            ViewData[Constants.PAGE_INDEX] = pageIndex;

            if (pageIndex > totalPage)
                return null;

            var lst = repository.Paging(productId, pageIndex, Constants.NUM_OF_ROWS);

            return lst;
        }
    }
}